<template>
  <van-address-list
    v-model="chosenAddressId"
    :list="list"
    @add="onAdd"
    @select="onSelect"
    @edit="onEdit"
  />
</template>
<script>
  import customerService from '../../api/customerService';
  export default {
    data() {
      return {
        chosenAddressId: '',
        list: []
      }
    },

    methods: {
      _getAddrs(){
        customerService.getCustomerAddrs().then((rsp)=>{
          if(rsp.result) {
          let addrList = rsp.obj;
          if(addrList && addrList.length>0) {
            for(let i=0;i<addrList.length;i++) {
              let addr = addrList[i];
              if(addr.defaultAddr == 0) {
                this.chosenAddressId = addr.id;
              }
              let obj = {
                id:addr.id,
                name:addr.name,
                tel:addr.mobile,
                address:`${addr.province}${addr.city}${addr.area}${addr.address}`
              };
              this.list.push(obj);
            }
          }
        }else {
          this.$toast(rsp.errorMsg);
        }
      }).catch((error)=>{
          this.$toast('getCustomerAddrs接口异常'+error);
      });
      },
      onAdd() {
        this.$nocacheRouter('/addAddr',this.$route.query);
      },
      onSelect(item) {
        customerService.setDefaultAddr({id:item.id}).then((rsp)=>{
          if(rsp.result) {
          this.$nocacheRouter('/pay',this.$route.query);
        }else {
          this.$toast(rsp.errorMsg);
        }
      }).catch((error)=>{
          this.$toast('setDefaultAddr接口异常'+error);
      });
      },
      onEdit(item, index) {
        this.$route.query.addrId = item.id;
        this.$nocacheRouter('/addAddr',this.$route.query);
      }
    },
    mounted(){
      this._getAddrs();
    }
  }
</script>
